// 设备连接页面
const api = require('../../utils/api')
const DeviceSyncManager = require('../../utils/deviceSync');

Page({
  data: {
    deviceList: [],
    scanning: false,
    scanButtonText: '搜索设备',
    deviceType: 'glucose', // 当前选择的设备类型
    connectedDevices: [], // 已连接的设备列表
    supportedDevices: [
      { type: 'glucose', name: '血糖仪', emoji: '🩸' },
      { type: 'bloodPressure', name: '血压计', emoji: '💓' },
      { type: 'weight', name: '体重秤', emoji: '⚖️' }
    ],
    editingDeviceId: '',
    editingDeviceName: '',
    showEditNameModal: false
  },

  onLoad(options) {
    // 初始化蓝牙适配器
    this.checkBluetoothAvailable();
    
    // 获取已连接设备列表
    this.fetchConnectedDevices();
    
    // 如果从健康页面带有设备类型参数跳转过来
    if (options.type) {
      this.setData({
        deviceType: options.type
      });
    }
  },
  
  // 获取已连接设备列表
  async fetchConnectedDevices() {
    try {
      // 调用API获取已连接设备列表
      const response = await api.device.getDevices();
      
      if (response.success) {
        const connectedDevices = response.data.devices.map(device => {
          // 格式化最后同步时间
          let lastSyncText = '未同步';
          if (device.lastSyncDate) {
            const syncDate = new Date(device.lastSyncDate);
            lastSyncText = `${syncDate.getMonth() + 1}月${syncDate.getDate()}日 ${syncDate.getHours()}:${String(syncDate.getMinutes()).padStart(2, '0')}`;
          }

          return {
            id: device._id,
            type: device.type,
            name: device.name,
            deviceId: device.deviceId, 
            addedAt: new Date(device.createdAt),
            customName: device.customName,
            lastSyncDate: device.lastSyncDate,
            lastSyncText: lastSyncText
          };
        });
        
        this.setData({ connectedDevices });
      } else {
        console.error('获取设备失败:', response.message);
        // 使用模拟数据作为后备
        this.setData({
          connectedDevices: []
        });
      }
    } catch (error) {
      console.error('获取已连接设备失败:', error);
      wx.showToast({
        title: '获取设备列表失败',
        icon: 'none'
      });
    }
  },

  // 检查蓝牙适配器是否可用
  checkBluetoothAvailable() {
    wx.showLoading({ title: '初始化中...' });
    wx.openBluetoothAdapter({
      success: (res) => {
        wx.hideLoading();
        console.log('蓝牙适配器已就绪', res);
        // 设置监听蓝牙设备被发现事件
        this.onDiscoveryDevices();
      },
      fail: (err) => {
        wx.hideLoading();
        console.error('蓝牙适配器不可用', err);
        wx.showModal({
          title: '提示',
          content: '请打开蓝牙后再试',
          showCancel: false
        });
      }
    });
  },

  // 选择设备类型
  selectDeviceType(e) {
    const type = e.currentTarget.dataset.type;
    
    // 设置当前选择的设备类型
    this.setData({
      deviceType: type
    });
    
    console.log('选择设备类型:', type);
    
    // 重置设备列表
    if (this.data.scanning) {
      this.stopScan();
    }
    
    this.setData({
      deviceList: []
    });
  },

  // 开始扫描设备
  startScan() {
    if (this.data.scanning) {
      this.stopScan();
      return;
    }

    this.setData({
      deviceList: [],
      scanning: true,
      scanButtonText: '停止搜索'
    });

    wx.showLoading({ title: '搜索中...' });

    // 开始搜索蓝牙设备
    wx.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: false,
      success: (res) => {
        console.log('开始搜索蓝牙设备', res);
        this.onDiscoveryDevices();
      },
      fail: (err) => {
        console.error('搜索蓝牙设备失败', err);
        this.stopScan();
        wx.showToast({
          title: '搜索失败，请重试',
          icon: 'none'
        });
      }
    });
  },

  // 停止扫描设备
  stopScan() {
    wx.stopBluetoothDevicesDiscovery({
      success: (res) => {
        console.log('停止搜索蓝牙设备', res);
      }
    });

    wx.hideLoading();
    this.setData({
      scanning: false,
      scanButtonText: '搜索设备'
    });
  },

  // 监听设备发现事件
  onDiscoveryDevices() {
    wx.onBluetoothDeviceFound((res) => {
      res.devices.forEach(device => {
        // 过滤没有名称或者信号过低的设备
        if (!device.name && !device.localName) return;
        if (device.RSSI < -90) return;
        
        // 更新设备列表
        this.updateDeviceList(device);
      });
    });
  },
  
  // 检查设备是否已连接
  isDeviceConnected(deviceId) {
    return this.data.connectedDevices.some(device => device.deviceId === deviceId);
  },

  // 连接设备
  async connectDevice(e) {
    const deviceId = e.currentTarget.dataset.id;
    const deviceName = e.currentTarget.dataset.name;
    
    // 检查是否已连接
    if (this.isDeviceConnected(deviceId)) {
      wx.showToast({
        title: '设备已连接',
        icon: 'none'
      });
      return;
    }
    
    // 检查设备类型是否已选择
    if (!this.data.deviceType) {
      wx.showModal({
        title: '提示',
        content: '请先选择设备类型',
        showCancel: false
      });
      return;
    }
    
    wx.showLoading({ title: '连接中...' });
    
    try {
      // 调用后端API添加设备
      const response = await api.device.addDevice({
        deviceId: deviceId,
        name: deviceName,
        type: this.data.deviceType
      });
      
      wx.hideLoading();
      
      if (response.success) {
        // 添加到已连接设备列表
        const newDevice = response.data;
        const connectedDevice = {
          id: newDevice._id,
          type: newDevice.type,
          name: newDevice.name,
          deviceId: newDevice.deviceId,
          addedAt: new Date(newDevice.createdAt),
          customName: newDevice.customName
        };
        
        const connectedDevices = [...this.data.connectedDevices, connectedDevice];
        
        this.setData({
          connectedDevices
        });
        
        // 提示成功
        wx.showToast({
          title: '设备连接成功',
          icon: 'success'
        });
        
        // 更新设备列表
        this.updateDeviceList();
        
        // 停止搜索
        this.stopScan();
        
        // 返回上一页
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      } else {
        wx.showToast({
          title: response.message || '连接失败',
          icon: 'none'
        });
      }
    } catch (error) {
      wx.hideLoading();
      console.error('连接设备失败:', error);
      wx.showToast({
        title: '连接失败，请重试',
        icon: 'none'
      });
    }
  },
  
  // 更新设备列表中的连接状态
  updateDeviceList(newDevice) {
    // 检查是否已存在该设备
    const { deviceList } = this.data;
    
    // 已存在则不添加
    if (deviceList.some(device => device.deviceId === newDevice.deviceId)) return;
    
    // 添加到设备列表并更新
    const isConnected = this.isDeviceConnected(newDevice.deviceId);
    this.setData({
      deviceList: [...deviceList, {...newDevice, isConnected}]
    });
  },
  
  // 删除设备
  async deleteDevice(e) {
    const deviceId = e.currentTarget.dataset.id;
    const deviceToDelete = this.data.connectedDevices.find(device => device.deviceId === deviceId);
    
    if (!deviceToDelete) {
      return;
    }
    
    wx.showModal({
      title: '删除设备',
      content: '确定要删除此设备吗？',
      success: async (res) => {
        if (res.confirm) {
          // 调用API删除设备
          try {
            wx.showLoading({ title: '处理中...' });
            
            const response = await api.device.deleteDevice(deviceToDelete.id);
            
            wx.hideLoading();
            
            if (response.success) {
              // 从列表中移除设备
              const connectedDevices = this.data.connectedDevices.filter(
                device => device.deviceId !== deviceId
              );
              
              this.setData({
                connectedDevices
              });
              
              // 更新设备列表
              this.updateDeviceList();
              
              wx.showToast({
                title: '设备已删除',
                icon: 'success'
              });
            } else {
              wx.showToast({
                title: response.message || '删除失败',
                icon: 'none'
              });
            }
          } catch (error) {
            wx.hideLoading();
            console.error('删除设备失败:', error);
            wx.showToast({
              title: '删除失败，请重试',
              icon: 'none'
            });
          }
        }
      }
    });
  },
  
  // 编辑设备名称
  editDeviceName(e) {
    const deviceId = e.currentTarget.dataset.id;
    const device = this.data.connectedDevices.find(d => d.deviceId === deviceId);
    
    if (device) {
      this.setData({
        editingDeviceId: device.id, // 使用MongoDB ID
        editingDeviceName: device.customName || device.name,
        showEditNameModal: true
      });
    }
  },
  
  // 取消编辑名称
  cancelEditName() {
    this.setData({
      showEditNameModal: false,
      editingDeviceId: '',
      editingDeviceName: ''
    });
  },
  
  // 确认编辑名称
  async confirmEditName() {
    if (!this.data.editingDeviceId) {
      this.cancelEditName();
      return;
    }
    
    try {
      wx.showLoading({ title: '保存中...' });
      
      // 调用API更新设备名称
      const response = await api.device.updateDevice(
        this.data.editingDeviceId,
        { customName: this.data.editingDeviceName }
      );
      
      wx.hideLoading();
      
      if (response.success) {
        // 更新本地数据
        const connectedDevices = this.data.connectedDevices.map(device => {
          if (device.id === this.data.editingDeviceId) {
            return {
              ...device,
              customName: this.data.editingDeviceName
            };
          }
          return device;
        });
        
        this.setData({
          connectedDevices,
          showEditNameModal: false,
          editingDeviceId: '',
          editingDeviceName: ''
        });
        
        wx.showToast({
          title: '设备名称已更新',
          icon: 'success'
        });
      } else {
        wx.showToast({
          title: response.message || '更新失败',
          icon: 'none'
        });
      }
    } catch (error) {
      wx.hideLoading();
      console.error('更新设备名称失败:', error);
      wx.showToast({
        title: '更新失败，请重试',
        icon: 'none'
      });
    }
  },
  
  // 处理名称输入
  onDeviceNameInput(e) {
    this.setData({
      editingDeviceName: e.detail.value
    });
  },

  // 同步设备数据
  async syncDeviceData(e) {
    const deviceId = e.currentTarget.dataset.id;
    const device = this.data.connectedDevices.find(item => item.id === deviceId);
    
    if (!device) {
      wx.showToast({
        title: '设备不存在',
        icon: 'none'
      });
      return;
    }
    
    wx.showLoading({
      title: '正在同步数据...',
      mask: true
    });
    
    try {
      // 调用设备同步管理器进行数据同步
      const result = await DeviceSyncManager.connectAndSync(device);
      
      wx.hideLoading();
      
      if (result.success) {
        wx.showToast({
          title: result.message,
          icon: 'success'
        });
        
        // 更新设备信息
        this.fetchConnectedDevices();
      } else {
        wx.showToast({
          title: result.message,
          icon: 'none'
        });
      }
    } catch (error) {
      wx.hideLoading();
      console.error('同步数据失败:', error);
      
      wx.showToast({
        title: '同步失败',
        icon: 'none'
      });
    }
  },

  onUnload() {
    // 停止蓝牙搜索
    if (this.data.scanning) {
      this.stopScan();
    }
  },
})